﻿using EntityFramework.Data.Core;
using Framework.Common.Exceptions;
using IRepositories.Core;
//*********************************************************************
//
//  文件名：MenuService
//
//  作者： LW
//
//  作用：
//
//  日期：2015/9/18 10:26:42
//
//*********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using YouTravel.DomainModels;
using YouTravel.Framework.Enums;
using YouTravel.Framework.Const;

namespace YouTravel.DomainService
{
    /// <summary>
    /// MenuService
    /// </summary>
    public class MenuService : IMenuService
    {
        readonly IEFRepository<Menu> _menuRepository;
        readonly IEFRepository<User> _userRepository;

        public MenuService(IUnitOfWork db, IEFRepository<Menu> menuRepository, IEFRepository<User> userRepository)
        {
            this._userRepository = userRepository;
            this._menuRepository = menuRepository;
            this._menuRepository.SetDbContext(db);
        }

        public List<Menu> GetUserMenu(int userId)
        {
            User single = this._userRepository.GetModel().Include(o => o.Menus).SingleOrDefault(c => c.ID == userId);
            if ((int)single.Type == 0)
            {
                return this._menuRepository.GetModel().Where(c => c.Status).OrderBy(c => c.Code).ThenBy(c => c.Sort).ToList();
            }
            else
            {
                if (single.Menus == null || single.Menus.Count() <= 0)
                    throw new BusinessException("未设置菜单权限");
                if (single.Type == UserType.SpecialLine && !single.IsSpecialManager)
                {
                    //如果是专线普通账号 则移除账号管控权限
                    if (single.Menus.Where(c => c.Code == BusinessConst.MENUCODE200).Count() > 0)
                        single.Menus.Remove(single.Menus.SingleOrDefault(c => c.Code == BusinessConst.MENUCODE200));
                    if (single.Menus.Where(c => c.Code == BusinessConst.MENUCODE201).Count() > 0)
                        single.Menus.Remove(single.Menus.SingleOrDefault(c => c.Code == BusinessConst.MENUCODE201));
                }
                return single.Menus.Where(c => c.Status).OrderBy(c => c.Code).ThenBy(c => c.Sort).ToList();
            }
        }

        public List<Menu> GetAllMenu()
        {
            return this._menuRepository.GetModel().Where(c => c.Status).OrderBy(c => c.Code).ThenBy(c => c.Sort).ToList();
        }
    }
}
